// 节流
// 高频事件触发后，n 秒内只执行一次，节流是稀释函数的执行频率;
// 场景：
//   1.懒加载、滚动加载、加载更多或监听滚动条位置；
//   2.百度搜索框，搜索联想功能；
//   3.防止高频点击提交，防止表单重复提交；
//   4.鼠标不断点击触发
//   5.resize

// 1.首节流[时间戳]  第一次会立即执行
const throttle1 = (fn, delay) => {
  let last;
  return function () {
    let now = Date().now();
    if (now - last > delay) {
      last = now;
      fn.apply(this, arguments);
    }
  };
};

// 2.尾节流[setTimeout] 不会立刻执行，会在delay之后执行
const throttle2 = (fn, delay) => {
  let timer = null;
  return function () {
    const args = arguments;
    const context = this;
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(context, args);
        timer = null;
      }, delay);
    }
  };
};

// 3.首尾节流 [ 时间戳 + setTimeout ]
const throttle = (fn, delay) => {
  let timer = null;
  let last = 0;
  return function () {
    const context = this;
    const args = arguments;
    let now = Date.now();
    timer && clearTimeout(timer);
    if (now - last >= delay) {
      fn.apply(context, args);
      last = Date.now();
    } else {
      const remain = delay - (now - last);
      timer = setTimeout(() => {
        fn.apply(context, args);
        last = Date.now();
      }, remain);
    }
  };
};
